package com.mydemo.controller;

import com.alibaba.cloud.ai.dashscope.embedding.DashScopeEmbeddingOptions;
import jakarta.annotation.Resource;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class Embed2VectorController {

    @Resource
    private EmbeddingModel embeddingModel;

    @Resource
    private VectorStore vectorStore;

    /**
     * 调用大模型，将文本向量化
     * @param msg
     * @return
     */
    @GetMapping("/text2Embed")
    public EmbeddingResponse text2Embed(String msg) {
        EmbeddingResponse embeddingResponse = embeddingModel.call(new EmbeddingRequest(List.of(msg),
                DashScopeEmbeddingOptions.builder()
                        .withModel("text-embedding-v3")
                        .build()));

        System.out.println(Arrays.toString(embeddingResponse.getResult().getOutput()));
        return embeddingResponse;
    }


    /**
     * 文本向量化，然后存入 redisstack
     */
    @GetMapping("/text2Embed/add")
    public void add(){
        //创建多个 Document 文档对象
        List<Document> documents= Arrays.asList(
                new Document("我想吃牛排"),
                new Document("我要吃蛋糕")
        );
        //将文档对象添加到向量数据库中
        vectorStore.add(documents);
     }

     /**
     * 在向量数据库中查找数据
     */
     @GetMapping("/text2Embed/get")
      public List getAll(@RequestParam(name = "msg") String msg){
         SearchRequest searchRequest = SearchRequest.builder()
                 .query(msg)
                 .topK(5)
                 .build();

         List<Document> documents = vectorStore.similaritySearch(searchRequest);

         return documents;
     }
}
